<template>
  <!-- 费用（条码申请项目） -->
  <div id="wLapplicationItem">
    <div style="text-align:right;margin-right:10px;">
      <vxe-button type="text" style="margin-right:5px;" class="button-blue" icon="vxe-icon-square-plus" content="补费" :disabled="isAlreadyChk" @click="addFee"></vxe-button>
      <vxe-button type='text' style="margin-right:5px;" icon='vxe-icon-delete' class='button-red' content='删除' :disabled="isAlreadyChk" @click='handleDelete'></vxe-button>
      <vxe-button type='text' class='button-blue' icon='vxe-icon-save' content='保存' :disabled="isAlreadyChk" @click='saveFee'></vxe-button>
    </div>
    <vxe-table ref="applicationItemTableList" v-loading="loading" border height="auto" :data="tableList" :footer-method="footerMethod" :merge-footer-items="[ { row: 0, col: 1, rowspan: 1, colspan: 5 } ]" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{
            isArrow: true,
            isTab: true,
            isEdit: true
          }" :edit-config="{ trigger: 'click', mode: 'cell', showIcon: false, showStatus: true }" footer-row-class-name="table-footer" show-footer resizable show-overflow>
      <vxe-column type="checkbox" fixed="left" width="26"></vxe-column>
      <vxe-column field="feeCode" title="编号" width="100"></vxe-column>
      <vxe-column field="feeName" title="收费项目" align="left" min-width="160"></vxe-column>
      <vxe-column field="amount" title="数量" width="80" :edit-render="{ autofocus: '.vxe-input--inner' }">
        <template #default="{ row }">
          <span>{{ row.amount ? row.amount : '' }}</span>
        </template>
        <template #edit="{ row }">
          <vxe-input v-model="row.amount" :disabled="row.isCharge==1||isAlreadyChk" type="number" min="0" @blur="editFee(row)"></vxe-input>
        </template>
      </vxe-column>
      <vxe-column field="price" title="单价" width="80" align="right"></vxe-column>
      <vxe-column field="costs" title="总金额" width="80" align="right"></vxe-column>
      <vxe-column field="isCharge" title="计费状态" width="80" align="right">
        <template #default="{ row }">
          <span v-if="row.isCharge==1" style="color:blue;">计费成功</span>
          <span v-else style="color:red;">未计费</span>
        </template>
      </vxe-column>
      <vxe-column field="message" title="失败原因" width="120" align="right" show-overflow-tooltip>
      </vxe-column>
    </vxe-table>

    <vxe-modal v-model="showStaData" title="收费项目" :mask="false" width="40vw" height="60vh" :destroy-on-close="true" show-zoom resize>
      <vxe-table ref="staTableRef" border="inner" align="left" :loading="feeloading" class="mytable-scrollbar" height="90%" :data="staTableData" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true, enabled: false }" show-header-overflow show-overflow keep-source>
        <vxe-column type="checkbox" fixed="left" width="26"></vxe-column>
        <vxe-column type="seq" title="#" width="30"></vxe-column>
        <vxe-column field="feeCode" title="项目编码" :edit-render="{ autofocus: '.vxe-input--inner' }">
        </vxe-column>
        <vxe-column field="feeName" title="项目名称" :edit-render="{ autofocus: '.vxe-input--inner' }">
        </vxe-column>
        <vxe-column field="price" title="单价" :edit-render="{ autofocus: '.vxe-input--inner' }">
        </vxe-column>
      </vxe-table>
      <div style="text-align:right;margin-right:10px; margin-top:5px;">
        <vxe-button type="text" class="button-blue" icon="vxe-icon-copy" style="margin-left:5px;" content="确定" @click="addFeeItems"></vxe-button>
      </div>
    </vxe-modal>
  </div>
</template>
<script setup lang="ts">
import { getCurrentInstance, reactive, ref } from 'vue';
import { Pane, Splitpanes } from 'splitpanes';
import { IsEmpty } from '@/utils/common';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import 'vxe-table/lib/style.css';

let { proxy }: any = getCurrentInstance();

let reqNo = ref(''); //接收传过来的检验结果id
let tableList = reactive([]);
let specAdditionList = reactive([]);
let loading = ref(false);
let additionLoading = ref(false);
let applicationItemTableList = ref(null);
let modalShow = ref(false);
let isNotEdit = false;
let isAlreadyChk = ref(false);
let costTotal = ref(0.0); /**费用合计 */
let specAdditionForm = reactive({
  reqNo: '', //条码号)
  rptGroup: '',
  sampleda: '',
  sampleNo: ''
}); //附加条码
let showStaData = ref(false);
let staTableRef = ref(null);
let staTableData = reactive([]);

defineExpose({
  getreqDetail,
  getCostTotal
});

// 页面加载列表
function getreqDetail(repData: any) {
  if (IsEmpty(repData) || !repData) {
    tableList.length = 0;
    return;
  }
  if (repData.isChk == 2) {
    isAlreadyChk.value = true;
  } else {
    isAlreadyChk.value = false;
  }
  reqNo.value = '';
  if (!IsEmpty(repData.reqNo)) {
    reqNo.value = repData.reqNo;
  }
  specAdditionForm.reqNo = repData.reqNo;
  specAdditionForm.rptGroup = repData.rptGroup;
  if (repData.sampleda.length == 10) {
    specAdditionForm.sampleda = repData.sampleda + ' 00:00:00';
  } else {
    specAdditionForm.sampleda = repData.sampleda;
  }
  specAdditionForm.sampleNo = repData.sampleNo;
  getDetail();
}

// 获取项目费用明细
function getDetail() {
  tableList.length = 0;
  loading.value = true;
  const url = '/bac/addFee/findBacAddFeeByMainInfo';
  proxy.$http
    .get(url, { params: { reqNo: specAdditionForm.reqNo, rptGroup: specAdditionForm.rptGroup, sampleda: specAdditionForm.sampleda, sampleNo: specAdditionForm.sampleNo } })
    .then(async (res: any) => {
      tableList.length = 0;
      Object.assign(tableList, res.data.bacAddFeeList);
      const errorList = res.data.bacAddFeeList.filter((p) => p.isCharge == 0 && p.message != null);
      let isAddFee = { addFeeCnt: res.data.bacAddFeeList.length, bacDrugCnt: res.data.bacDrugCnt, errorCnt: errorList.length };
      proxy.$emit('getAddFeeCnt', isAddFee);

      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage(err, VxeNotifyType.error);
    });
}

function editFee(row) {
  row.costs = row.amount * row.price;
  // const url = '/bac/addFee/editFee';
  // proxy.$http.post(url, row).then((res: any) => {});
}

function addFee() {
  getFeeItem();
  showStaData.value = true;
}

function saveFee() {
  const dataList = tableList.filter((p) => p.isCharge != 1);
  if (!dataList) {
    VxeMessage('未添加新的补费信息', VxeNotifyType.warning);
    return;
  }
  console.log(dataList);
  const url = '/bac/addFee/batchAddFeeList';
  proxy.$http
    .post(url, dataList)
    .then((res: any) => {
      getDetail();
      VxeMessage('保存成功!', VxeNotifyType.success);
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

async function getFeeItem() {
  staTableData.length = 0; //放入数据前清空数据

  const commaSeparatedIds = tableList.map((row) => row.feeCode);
  const feeCodes = commaSeparatedIds.join(',');
  const data = { feeCodes: feeCodes };

  const url = '/bac/addFee/findBacAddFeeItem';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: data })
    .then(async (res: any) => {
      staTableData.length = 0; //放入数据前清空数据
      if (res.data && res.data.length > 0) {
        staTableData.push(...res.data);
      }
    })
    .catch((err: any) => {
      staTableData.length = 0; //放入数据前清空数据
      VxeMessage('获取申请项目异常', VxeNotifyType.error);
    });
}

async function addFeeItems() {
  let arr = await staTableRef.value?.getCheckboxRecords(true);
  if (!(arr.length > 0)) {
    VxeMessage('请勾选要补费的项目', VxeNotifyType.info);
  } else {
    //自动计算出应该补费的数量
    arr.forEach((element) => {
      element.id = '';
      element.rptGroup = specAdditionForm.rptGroup;
      element.reqNo = specAdditionForm.reqNo;
      element.sampleda = specAdditionForm.sampleda;
      element.sampleNo = specAdditionForm.sampleNo;
      element.amount = 1;
      element.costs = element.price;
    });
    const url = '/bac/addFee/countFeeItemsNum';
    proxy.$http
      .post(url, arr)
      .then((res: any) => {
        if (res.data && res.data.length > 0) {
          tableList.push(...res.data);
          showStaData.value = false;
        }
      })
      .catch((err: any) => {
        showStaData.value = false;
        VxeMessage('添加申请补费项目异常', VxeNotifyType.error);
      });
  }
}

//删除按钮
function handleDelete() {
  const selectRows = (proxy.$refs.applicationItemTableList as any).getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请勾选需要删除的数据', VxeNotifyType.warning);
    return;
  } else {
    const data = [];
    const removeList = [];
    selectRows.forEach((element) => {
      if (element.id) {
        data.push(element);
      } else {
        removeList.push(element);
      }
    });
    if (removeList && removeList.length > 0) {
      for (const removeRow of removeList) {
        const iindex = tableList.findIndex((item) => item == removeRow);
        tableList.splice(iindex, 1);
      }
    }
    if (data && data.length > 0) {
      proxy
        .$confirm('您确定要删除当前选中的数据吗，删除会退费?', '提示', {
          cancelButtonClass: 'cancel-button',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          const commaSeparatedIds = selectRows.map((row) => row.id);
          const ids = commaSeparatedIds.join(',');
          const data = { ids: ids };
          const url = '/bac/addFee/deleteAddFee';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              getDetail();
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        });
    }
  }
}

// 表尾
function footerMethod({ columns, data }) {
  let count = 0;
  tableList.forEach((item) => {
    count += item.price ? parseFloat(item.price) : 0;
  });
  costTotal.value = count;
  return [
    columns.map((column, _columnIndex) => {
      if (_columnIndex === 1) {
        return `金额合计: ${formatJe(count)}`;
      }
      return null;
    })
  ];
}
/**主界面获取费用合计 */
function getCostTotal() {
  return costTotal.value;
}
function formatJe(v) {
  if (Number.isNaN(v)) {
    return '';
  }
  return Number(v).toFixed(2);
}
</script>
<style lang="scss" scoped>
#wLapplicationItem {
  height: 100%;
}
</style>